package cn.itcast.util;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.IOException;

public class HttpRequest {

    public static final String post(String url, String params, int timeout)
            throws IOException {
        String responseMsg = "";
        // 构造HttpClient的实例
        HttpClient httpClient = new HttpClient();
        // 设置编码格式
        httpClient.getParams().setContentCharset("UTF-8");
        // 构造PostMethod的实例
        PostMethod postMethod = new PostMethod(url);
        // postMethod.set
        postMethod.setRequestHeader("Content-Type",
                "application/json");
        if (timeout <= 0) {
            timeout = 5000;
        }

        //postMethod.setRequestBody(params);
        postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
        RequestEntity requestEntity = new StringRequestEntity(params, "application/json", "UTF-8");
        postMethod.setRequestEntity(requestEntity);
        // http client 参数设置 连接超时 读取数据超时
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(timeout);

        try {
            // 执行postMethod,调用http接口
            httpClient.executeMethod(postMethod);
            // 读取内容
            responseMsg = "" +postMethod.getStatusCode();
        } catch (HttpException e) {
            //e.printStackTrace(); by zyf
            throw e;
        } catch (IOException e) {
            // e.printStackTrace();by zyf
            throw e;
        } finally {
            // 释放连接
            postMethod.releaseConnection();
            httpClient.getHttpConnectionManager().closeIdleConnections(0);
        }
        return responseMsg;

    }

}
